<?php

namespace addons\booking\controller;

use addons\booking\model\Cart as CartModel;
use addons\booking\model\Goods;
use addons\booking\model\Order;
use addons\booking\model\UserCoupon;

/**
 * 购物车
 */
class Cart extends Base
{
    protected $noNeedLogin = [];

    /**
     * 添加购物车
     */
    public function add()
    {
        $sceneval = $this->request->post('sceneval'); //1,只加入购物车,2,加入后提交订单
        $goods_id = $this->request->post('goods_id');
        if (!$goods_id) {
            $this->error('参数错误');
        }
        $goods = Goods::get($goods_id);
        if (!$goods || $goods['status'] != 'up') {
            $this->error('商品不存在');
        }
        if ($goods['stocks'] <= 0) {
            $this->error('商品没有库存了');
        }
        $cart_id = CartModel::add($goods_id, $this->auth->id, $sceneval);
        if ($cart_id) {
            $this->success('添加购物车成功', $cart_id);
        }
        $this->error('添加购物车失败');
    }

    /**
     * 购物车列表
     */
    public function index()
    {
        $id = $this->request->post('id');
        $sceneval = $this->request->post('sceneval', 1);
        $to_order = $this->request->post('order');
        //获取最后的可入住的房间号
        $order = Order::alias('o')
            ->join('booking_house h', 'o.source_id=h.id')
            ->field('h.room')
            ->where('o.type', 0)
            ->where('o.status', 'checkined')
            ->where('o.user_id', $this->auth->id)
            ->find();

        $data = ['house' => $order];
        $data['list'] = CartModel::tableList($this->auth->id, $id, $sceneval);
        ///我的，可以用的优惠券
        if (!empty($to_order)) {
            $goods_ids = array_column($data['list'], 'goods_id');
            $data['coupons'] = UserCoupon::myGoodsCoupon($this->auth->id, $goods_ids);
        }
        $this->success('获取成功', $data);
    }

    //删除购物车
    public function del()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }
        CartModel::where('user_id', $this->auth->id)->where('id', 'IN', $id)->delete();
        $this->success('删除成功');
    }


    /**
     * 购物车商品数量+-
     */
    public function set_nums()
    {
        $id = $this->request->post('id');
        $nums = (int)$this->request->post('nums');
        if (!$id || !$nums) {
            $this->error('参数错误');
        }
        $row = CartModel::with('Goods')->where('id', $id)->where('user_id', $this->auth->id)->find();
        if (!$row) {
            $this->error('未找到记录');
        }
        if ($row->goods->stocks < $nums) {
            $this->error('库存不足');
        }
        $row->nums = $nums;
        $row->save();
        $this->success('操作成功');
    }

    /**
     * 获取购物车数量
     */
    public function cart_nums()
    {
        $total = CartModel::where('user_id', $this->auth->id)->where('sceneval', 1)->count();
        $this->success('', $total);
    }
}
